class MonitorComponent {
  constructor(containerId = 'content') {
    this.container = document.getElementById(containerId);
    this.template = null;
    this.ws = null;
    //this.initWebSocket();
    this.init();
  }

  async init(){
    await this.loadTemplate();
    this.renderSkeleton();
    this.renderData({});
    this.bindEvents();
  }

  async loadTemplate() {
    const response = await fetch('/static/templates/monitor-template.html');
    this.template = await response.text();
  }

  renderSkeleton() {
    this.container.innerHTML = this.template;
  }

  renderData(data) {
    //this.container.innerHTML = Handlebars.compile(this.template)(data);
  }

  bindEvents() {
    // this.container.querySelectorAll('.control-buttons button').forEach(btn => {
    //   btn.addEventListener('click', () => this.handleControl(btn.dataset.action));
    // });
    const btncontainer = document.getElementById('control-buttons');
    btncontainer.querySelector('.start-btn')?.addEventListener('click', async () => {
      const response = await fetch('/api/startHalfMarathon');
    });
    btncontainer.querySelector('.stop-btn')?.addEventListener('click', async () => {
      const response = await fetch('/api/stopHalfMarathon');
    });
    btncontainer.querySelector('.resetmatch-btn')?.addEventListener('click', async () => {
      const response = await fetch('/api/resetMatch');
    });
  }

  handleControl(action) {
    this.ws.send(JSON.stringify({ type: 'control', action }));
  }

  initWebSocket() {
    this.ws = new WebSocket(`ws://${location.host}/ws/monitor`);
    this.ws.onmessage = (event) => {
      this.updateStatus(JSON.parse(event.data));
    };
  }

  updateStatus(data) {
    document.getElementById('server-status').textContent = data.status;
    document.querySelectorAll('.stats-cards .number').forEach((el, index) => {
      el.textContent = data.stats[index];
    });
  }
}

window.MonitorComponent = MonitorComponent;